/* eslint-disable no-param-reassign */
import { RuntimeModelError } from '@ibiz-template/core';
import {
  ButtonContainerState,
  UIActionButtonState,
  UIActionUtil,
} from '@ibiz-template/runtime';
import { IDEGridUAColumn, IUIActionGroupDetail } from '@ibiz/model-core';
import { GridColumnController } from '../../grid/grid-column.controller';
import { GridRowState } from '../../grid/grid-row.state';

/**
 * 表格操作列控制器
 * @return {*}
 * @author: zhujiamin
 * @Date: 2022-09-01 18:25:20
 */
export class GridUAColumnController extends GridColumnController<IDEGridUAColumn> {
  /**
   * 给rowController初始化操作列的状态
   *
   * @author lxm
   * @date 2022-09-07 21:09:43
   * @param {GridRowState} row
   */
  initActionStates(row: GridRowState): void {
    // 操作列按钮状态控制
    const { deuiactionGroup } = this.model;
    if (!deuiactionGroup) {
      throw new RuntimeModelError(this.model, '操作列没有配置界面行为组');
    }
    if (!deuiactionGroup.uiactionGroupDetails?.length) {
      ibiz.log.debug('操作列界面行为组没有配置界面行为');
      return;
    }
    const containerState = new ButtonContainerState();
    deuiactionGroup.uiactionGroupDetails.forEach(detail => {
      const actionid = detail.uiactionId;
      if (actionid) {
        const buttonState = new UIActionButtonState(
          detail.id!,
          this.grid.context.srfappid!,
          actionid,
        );
        containerState.addState(detail.id!, buttonState);
      }
    });
    row.uaColStates[this.model.codeName!] = containerState;
  }

  /**
   * 触发操作列点击事件
   *
   * @author lxm
   * @date 2022-09-07 22:09:46
   * @param {IPSUIActionGroupDetail} detail
   * @param {MouseEvent} event
   */
  async onActionClick(
    detail: IUIActionGroupDetail,
    row: GridRowState,
    event: MouseEvent,
  ): Promise<void> {
    const actionId = detail.uiactionId;
    // 行编辑切换直接调表格方法，不走视图逻辑
    if (actionId === 'ToggleRowEdit') {
      await this.grid.toggleRowEdit(row);
      return;
    }

    await UIActionUtil.execAndResolved(actionId!, {
      context: this.context,
      params: this.params,
      data: [row.data],
      view: this.grid.view,
      event,
    });
  }
}
